package helperService

import (
	"errors"
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"gitee.com/yangguoliang001/go-gin-vue3/vo"
	"github.com/gin-gonic/gin"
)

func (h helperService) SearchCache(c *gin.Context, cacheReq QO.CacheReq) (searchRes vo.SearchCacheVO, err error) {
	if b := h.cache.Exists(cacheReq.RedisKey); b.Val() == 0 {
		response.Fail(c, code.CacheNotExist, code.Text(code.CacheNotExist), gin.H{"realErr": b.Err()})
		return vo.SearchCacheVO{}, errors.New("不存在")
	}

	res := h.cache.Get(cacheReq.RedisKey)
	ttlRes := h.cache.TTL(cacheReq.RedisKey)
	if res.Err() != nil {
		response.Fail(c, code.CacheGetError, code.Text(code.CacheGetError), gin.H{"realErr": err})
		return vo.SearchCacheVO{}, errors.New("获取缓存失败")
	}
	return vo.SearchCacheVO{
		Val: res.Val(),
		TTL: ttlRes.String(),
	}, err
}

func (h helperService) ClearCache(c *gin.Context, cacheReq QO.CacheReq) (clearRes vo.ClearCacheVO, err error) {

	if b := h.cache.Exists(cacheReq.RedisKey); b.Val() == 0 {
		response.Fail(c, code.CacheNotExist, code.Text(code.CacheNotExist), gin.H{"realErr": b.Err()})
		return vo.ClearCacheVO{}, errors.New("不存在")
	}
	if b := h.cache.Del(cacheReq.RedisKey); b.Val() == 0 {
		response.Fail(c, code.CacheDelError, code.Text(code.CacheDelError), gin.H{"realErr": b.Err()})
		return vo.ClearCacheVO{}, errors.New("删除失败")
	}
	return vo.ClearCacheVO{
		Bool: true,
	}, nil
}
